package com.library.servlet;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.library.dao.UserDAO;
import com.library.entity.User;
import com.library.util.DateUtil;

/**
 * 注册处理Servlet
 */
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 设置请求和响应的字符编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        
        // 获取表单数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String realName = request.getParameter("realName");
        String email = request.getParameter("email");
        String phone = request.getParameter("phone");
        
        // 检查用户名是否已存在
        UserDAO userDAO = new UserDAO();
        User existingUser = userDAO.getUserByUsername(username);
        
        if (existingUser != null) {
            // 用户名已存在，返回注册页面并显示错误信息
            request.setAttribute("error", "用户名已存在，请选择其他用户名");
            request.getRequestDispatcher("register.jsp").forward(request, response);
            return;
        }
        
        // 创建新用户
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setRealName(realName);
        user.setEmail(email);
        user.setPhone(phone);
        user.setRole(1); // 普通用户
        user.setRegisterTime(DateUtil.formatDate(new Date()));
        
        // 添加用户到数据库
        boolean success = userDAO.addUser(user);
        
        if (success) {
            // 注册成功，重定向到登录页面
            response.sendRedirect("login.jsp");
        } else {
            // 注册失败，返回注册页面并显示错误信息
            request.setAttribute("error", "注册失败，请稍后再试");
            request.getRequestDispatcher("register.jsp").forward(request, response);
        }
    }
}
